// SkypePluginB.h : Declaration of the CSkypePluginB

#pragma once

#include "sdk-skype/Wi2Geo.Skype_h.h"
#include "SkypeController.h"
#include "PluginBase.h"

// CSkypePluginB

class ATL_NO_VTABLE CSkypePluginB
	: public CPluginBase
	, public ATL::CComObjectRootEx<ATL::CComSingleThreadModel>
	, public ISkypePluginB
{
	ATL::CComPtr<ICollectionManager> m_pCollectionManager;
	ATL::CComBSTR                    m_bstrItemID;
	HWND                             m_hMainSkypeWindow;
	CSkypeController                 m_ctl;

	void Error(LPCTSTR szMessage)
	{
		MessageBox(m_hMainSkypeWindow, szMessage, NULL, MB_OK | MB_ICONERROR);
	}

public:
	CSkypePluginB();

BEGIN_COM_MAP(CSkypePluginB)
	COM_INTERFACE_ENTRY(ISkypePluginB)
END_COM_MAP()

	const _tstring ReadIniFileSetings
		( IN LPCTSTR szName
		) const;

	void WriteIniFileSetings
		( IN LPCTSTR szName
		, IN _tstring strValue
		) const;

	virtual const std::string GetUserName() const
	{
		return (LPCSTR)ATL::CT2AEX<64>(ReadIniFileSetings(_T("UserName")).c_str(), CP_UTF8);
	}

	virtual const std::string GetPasswordHash() const
	{
		return (LPCSTR)ATL::CT2AEX<64>(ReadIniFileSetings(_T("PasswordHash")).c_str(), CP_UTF8);
	}

	virtual void OnSetLocation
		( IN const std::string& strLocation
		)
	{
		const std::string cmdPrefix("SET PROFILE RICH_MOOD_TEXT ");

		if (!m_ctl.SendCommand(cmdPrefix + strLocation)
			&& ERROR_INVALID_WINDOW_HANDLE == ::GetLastError())
		{
			// Skype may ban us due to slow response.
			//
			ATLTRACE(_T("Reconnect to skype\n"));
			m_ctl.Discover();
		}
	}

	HRESULT Init
		( IN const BSTR wzItemID
		, IN ICollectionManager *pCollectionManager
		, IN const BSTR /*wzParams*/
		)
	{
		if (pCollectionManager == NULL || wzItemID == NULL)
			return E_INVALIDARG;

		m_bstrItemID = wzItemID;
		m_pCollectionManager = pCollectionManager;
		return S_OK;
	}

	DWORD WINAPI Process();

public:
	STDMETHOD(Open)
		( IN POPEN_CONTEXT pOpenContext
		);

	STDMETHOD(ShowSettingsDlg)
		( IN OLE_HANDLE hWndOwner
		);

	STDMETHOD(Finalize)();
};

typedef ATL::CComObject<CSkypePluginB> CoSkypePluginB;
